/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Global;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class ConnectDB {
    public static Connection cn;
    
    private String url;
    private String portNumber;
    private String serverName;
    private String instanceName;
    private String databaseName;
    private String account;
    private String password;
    
    public ConnectDB(String port, String server, String instance, String database, String user, String pass){
        cn = null;
        this.portNumber = port;
        this.serverName = server;
        this.instanceName = instance;
        this.databaseName = database;
        this.account = user;
        this.password = pass;
        this.url = "jdbc:sqlserver://" + this.serverName + ";instanceName=" +
        this.instanceName + ";database=" + this.databaseName;
    }
    
    public void openConnection(){
        if(cn == null){
        try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            cn = DriverManager.getConnection(url, account, password);
            
        }catch (SQLException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Can not find the specific jdbc driver for SQL Server!");
        }catch (ClassNotFoundException ex){
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Can not find the specific jdbc driver for SQL Server!");
        }
        }
    }
    
    //disconnect from database
    public void closeConnection(){
        if(cn != null){
            try{
            cn.close();
            cn = null;
            System.out.println("Disconnect sucessfull!");
        }catch(SQLException ex){
        ex.printStackTrace();
        }
        }
    }
}
